import network
from time import sleep

#class Wlan:
#	def __init__(self):
#		pass

def set_ap_mode(ssid: str, password: str = "12345678", hidden: bool = False):
	new_access_point = network.WLAN(network.AP_IF)

	new_access_point.active(False)
	new_access_point.active(True)

	# 如果调用函数未指定 essid，则 essid 为 MicroPy- 加设备 mac 地址后6位
	if (ssid == ""):
		mac = new_access_point.config("mac")
		ssid = "MicroPy-%02x%02x%02x" % (mac[-3], mac[-2], mac[-1])

	new_access_point.config(essid = ssid, password = password, hidden = hidden)

	print("\n\nWifi access point intialized:\n    ssid: %s\n    password: %s" % (ssid, password))

def set_sta_mode(ssid: str, password: str):
	new_station = network.WLAN(network.STA_IF)

	new_station.active(False)
	new_station.active(True)

	print("\nConnecting to network...")

	new_station.connect(ssid, password)

	result_msg = ""
	ip_address = ""

	while (not new_station.isconnected()):
		result_code = new_station.status()

		if (result_code == network.STAT_IDLE):
			break
		elif (result_code == network.STAT_CONNECT_FAIL):
			break
		elif (result_code == network.STAT_CONNECTING):
			pass
		elif (result_code == network.STAT_GOT_IP):
			break
		elif (result_code == network.STAT_NO_AP_FOUND):
			break
		elif (result_code == network.STAT_WRONG_PASSWORD):
			break

		sleep(0.5)

	result_code = new_station.status()

	if (result_code == network.STAT_IDLE):
		result_msg = "network idle"

		print("network idle")
	elif (result_code == network.STAT_CONNECT_FAIL):
		result_msg = "network connect failed"

		print("network connect failed")
	elif (result_code == network.STAT_GOT_IP):
		result_msg = "got an ip"
	elif (result_code == network.STAT_NO_AP_FOUND):
		result_msg = "could not found ap"

		print("cannot found ap")
	elif (result_code == network.STAT_WRONG_PASSWORD):
		result_msg = "wrong password given"

		print("wrong password given")

	if (result_code == network.STAT_GOT_IP):
		ip_address = new_station.ifconfig()[0]

		print("network config:", new_station.ifconfig())

	return result_code, result_msg, ip_address
